import 'dart:typed_data';

import 'package:baseProjectFlutter/utils/hex/hex_utils.dart';

extension ListExtension<T> on List<T> {
  T? getOrNull(int index) {
    return length > index ? this[index] : null;
  }
}

extension IterableExtension<T> on Iterable<T> {
  T? firstWhereX(bool Function(T element) test, {T? defaultValue}) {
    try {
      return firstWhere(test);
    } catch (e) {
      return defaultValue;
    }
  }

  List<T> sortedBy<R>(R? Function(T element) selector) {
    final List<T> list = toList();
    list.sort((a, b) {
      final R? valueA = selector(a);
      final R? valueB = selector(b);

      if (valueA == null && valueB == null) return 0;
      if (valueA == null) return 1;
      if (valueB == null) return -1;
      if (valueA is Comparable<R> && valueB is Comparable<R>) {
        return valueA.compareTo(valueB);
      } else if (valueA is num && valueB is num) {
        return valueA.compareTo(valueB);
      } else if (valueA is bool && valueB is bool) {
        return valueA ? -1 : 1;
      } else {
        throw ArgumentError('Selector must return a Comparable type');
      }
    });
    return list;
  }
}

extension StringExtensions on String {
  /// 将String转化成ASCII byte[]
  ///
  /// @param res 要转化的String
  /// @return 对应的字符串
  Uint8List strToASCII() {
    return byteArrayOf(this.codeUnits);
  }
}

extension Run<T> on T {
  R run<R>(R Function(T it) block) {
    return block(this);
  }
}

extension Let<T> on T {
  R let<R>(R Function(T it) block) {
    return block(this);
  }
}

extension Apply<T> on T {
  T apply(void Function(T it) block) {
    block(this);
    return this;
  }
}

extension Also<T> on T {
  T also(void Function(T it) block) {
    block(this);
    return this;
  }
}

class Pair<A, B> {
  final A first;
  final B second;

  Pair(this.first, this.second);
}

extension StringNullExt on String? {
  String orEmpty() {
    return this ?? "";
  }
}

extension StringExt on String {
  String ifEmpty(String defaultValue) {
    return isEmpty ? defaultValue : this;
  }
}

main() {
  final list = [1, 2, 3, 4, 5];
  final result = list.firstWhereX((element) => element > 13);
  print(result);

  final List<Map<String, dynamic>> items = [
    {'name': 'Alice', 'age': 30, 'ccc': false},
    {'name': 'Bob', 'age': 25, 'ccc': false},
    {'name': 'David', 'age': 35, 'ccc': true},
    {'name': 'Charlie', 'age': null, 'ccc': null},
  ];

  final List<Map<String, dynamic>> sortedItems = items.sortedBy((item) => item['age'] as num?);

  print(sortedItems);
}
